<template>
  <div class="article-management">
    <h1>文章管理</h1>

    <!-- 搜索框 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="请输入标题、作者或状态"
        clearable
        @clear="handleSearch"
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </template>
      </el-input>
    </div>

    <!-- 添加文章按钮 -->
    <el-button type="primary" @click="handleAddArticle">添加文章</el-button>

    <!-- 文章列表表格 -->
    <el-table :data="filteredArticles" style="width: 100%" v-loading="loading">
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="slug" label="URL 别名" />
      <el-table-column prop="sourceUrl" label="语雀 URL" />
      <el-table-column prop="embedType" label="文档类型" />
      <el-table-column prop="authorName" label="作者" />
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="statusTagType(row.status)">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="publishedAt" label="发布时间">
        <template #default="{ row }">
          {{ formatDate(row.publishedAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="danger" size="small" @click="handlePush(row.id)">发布</el-button>
          <el-button type="primary" size="small" @click="handleEdit(row.id)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, onMounted, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';

interface Article {
  id: number;
  title: string;
  slug: string;
  sourceUrl: string;
  embedType: string;
  authorName: string;
  status: string;
  publishedAt: string;
}

export default defineComponent({
  name: 'ArticleManagement',
  setup() {
    const articles = ref<Article[]>([]); // 文章列表数据
    const loading = ref(false); // 加载状态
    const searchQuery = ref(''); // 搜索关键词
    const router = useRouter();
    const { proxy } = getCurrentInstance() as any; // 获取当前组件实例

    // 获取文章列表
    const fetchArticles = async () => {
      loading.value = true;
      try {
        const response = await proxy.$axios.get('/api/articles');
        console.log('API 返回的数据:', response.data); // 打印 API 返回的数据
        articles.value = response.data;
      } catch (error) {
        console.error('获取文章列表失败:', error); // 打印错误信息
        ElMessage.error('获取文章列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 删除文章
    const handleDelete = async (id: number) => {
      try {
        await ElMessageBox.confirm('确定删除该文章吗？', '提示', {
          type: 'warning',
        });
        await proxy.$axios.delete(`/api/articles/${id}`);
        ElMessage.success('删除成功');
        fetchArticles(); // 刷新文章列表
      } catch (error) {
        ElMessage.error('删除失败');
      }
    };

    // 发布文章
    const handlePush = async (id: number) => {
      try {
        await ElMessageBox.confirm('确定发布该文章吗？', '提示', {
          type: 'warning',
        });
        await proxy.$axios.post(`/api/articles/push/${id}`);
        ElMessage.success('发布成功');
        fetchArticles(); // 刷新文章列表
      } catch (error) {
        ElMessage.error('发布失败');
      }
    };

    // 编辑文章
    const handleEdit = (id: number) => {
      router.push(`/admin/articles/edit/${id}`);
    };

    // 添加文章
    const handleAddArticle = () => {
      router.push('/admin/articles/add');
    };

    // 根据状态返回标签类型
    const statusTagType = (status: string) => {
      switch (status) {
        case 'published':
          return 'success';
        case 'draft':
          return 'warning';
        case 'archived':
          return 'info';
        default:
          return '';
      }
    };

    // 格式化日期
    const formatDate = (dateString: string) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString();
    };

    // 处理搜索
    const handleSearch = () => {
      // 搜索逻辑已经在 computed 中实现，这里只需触发重新计算
    };

    // 根据搜索关键词过滤文章列表
    const filteredArticles = computed(() => {
      if (!searchQuery.value) {
        return articles.value; // 如果没有搜索关键词，返回全部文章
      }
      const query = searchQuery.value.toLowerCase();
      return articles.value.filter(
        (article) =>
          article.title.toLowerCase().includes(query) || // 匹配标题
          article.authorName.toLowerCase().includes(query) || // 匹配作者
          article.status.toLowerCase().includes(query) // 匹配状态
      );
    });

    // 组件挂载时获取文章列表
    onMounted(() => {
      fetchArticles();
    });

    return {
      articles,
      loading,
      searchQuery,
      filteredArticles,
      handleDelete,
      handlePush,
      handleEdit,
      handleAddArticle,
      handleSearch,
      statusTagType,
      formatDate,
    };
  },
});
</script>

<style scoped>



.article-management {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-bar {
  margin-bottom: 20px;
  max-width: 400px;
}
</style>